#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <MessageFrame.h>
#include <iostream>
#include "RoadSideInformation.h"
#include "rsi_test.h"
#include "bsm_test.h"
#include "rsm_test.h"
#include "spat_test.h"
#include "map_test.h"

using namespace std;

extern MessageFrame_t message_frame;

typedef enum OutRule {
    DER,
    OER,
    PER,
    XER
} e_OutRule;

static int save_to_file(const void *data, size_t size, void *key) {
    FILE *fp = (FILE *) key;
    return (fwrite(data, 1, size, fp) == size) ? 0 : -1;
}


int struct_to_file(MessageFrame_t *pFrame, char *outP, e_OutRule rule) {
    FILE *fpBin;
    fpBin = fopen(outP, "w+");
    asn_enc_rval_t er;

    switch (rule) {
        case DER:
            er = der_encode(&asn_DEF_MessageFrame, pFrame, save_to_file, fpBin);
            break;
        case OER:
            er = oer_encode(&asn_DEF_MessageFrame, pFrame, save_to_file, fpBin);
            break;
        case PER:
            er = uper_encode(&asn_DEF_MessageFrame, nullptr, pFrame, save_to_file, fpBin);
            break;
        case XER:
            er = xer_encode(&asn_DEF_MessageFrame, pFrame, XER_F_BASIC, save_to_file, fpBin);
            break;
        default:
            er.encoded = -1;
            break;
    }
    if (er.encoded == -1) {
        fprintf(stderr, "Cannot encode %s: %s\n", er.failed_type->name, strerror(errno));
        return -1;
    } else {
/* Return the number of bytes */
        return er.encoded;
    }
}

int rsi_struct_to_ber_file(MessageFrame_t *pFrame) {
    char out_file_name[] = "/home/zhuruyi/v2x/selfTest/testFile/rsi.der";
    struct_to_file(pFrame, out_file_name, DER);
}


int main(int ac, char **av) {
    //per rsi.bin to xml
//    char perRsi[] = "/home/zhuruyi/v2x/selfTest/rsi.bin";
//    char outXmlRsi[] = "/home/zhuruyi/v2x/selfTest/rsi.xml";
//    PER_to_XER(perRsi, outXmlRsi);
//
//    // xml to per rsi.bin
//    char xmlRsi[] = "/home/zhuruyi/v2x/selfTest/rsi.xml";
//    char outRsi[] = "/home/zhuruyi/v2x/selfTest/rsi2.bin";
//    XML_to_RSI(xmlRsi, outRsi);

//    test_bsm();

    test_rsi();
    char outFile[] = "/home/zhuruyi/v2x/selfTest/testFile/rsi.der";
    struct_to_file(&message_frame, outFile, DER);

//    test_rsm();

//    MessageFrame *messageFrame = test_spat();


//    test_map();
    return 0; /* Decoding finished successfully */
}
